package cn.itcast.controller.aoplog;

import cn.itcast.domain.syslog.SysLog;
import cn.itcast.domain.user.User;
import cn.itcast.service.system.SysLogService;
import org.aspectj.lang.ProceedingJoinPoint;
import org.aspectj.lang.annotation.Around;
import org.aspectj.lang.annotation.Aspect;
import org.aspectj.lang.reflect.MethodSignature;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Component;
import org.springframework.web.bind.annotation.RequestMapping;

import javax.servlet.http.HttpServletRequest;
import java.lang.reflect.Method;
import java.util.Date;
import java.util.UUID;

@Component
@Aspect
public class Log {

    @Autowired
    private SysLogService sysLogService;

    @Autowired
    private HttpServletRequest request;

    @Around("execution(* cn.itcast.controller.*.*.*(..))")
    public Object aroud(ProceedingJoinPoint pjp) throws Throwable {
        // 获取方法对象
        MethodSignature signature =(MethodSignature)pjp.getSignature();
        Method method = signature.getMethod(); //获取方法对象
        RequestMapping annotation = method.getAnnotation(RequestMapping.class); //获取方法的注解
        boolean flg = method.isAnnotationPresent(RequestMapping.class); //判断方法头上是否有指定注解
        if(flg){
            // 整理日志数据
            SysLog log = new SysLog();
            log.setId(UUID.randomUUID().toString().replace("-","")); //主键
            log.setTime(new Date()); //时间
            String ip = request.getRemoteAddr(); //场景：投票系统
            log.setIp(ip);  //ip
            User user=(User)request.getSession().getAttribute("loginUser");
            log.setUserName(user.getUserName());
            log.setCompanyId(user.getCompanyId());
            log.setCompanyName(user.getCompanyName());
            log.setMethod(method.getName());
            log.setAction(annotation.name());
            // 保存日志
            sysLogService.save(log);
        }
        // 让原方法执行
        return pjp.proceed();
    }
}
